import { connect } from 'react-redux';
import { useTranslation } from 'react-i18next';
import React, { useState, useEffect } from 'react';
import { View, TouchableOpacity, Text, TextInput, StyleSheet, Modal, TouchableWithoutFeedback, Image, FlatList } from 'react-native';
import { handleSetLang } from '@/store/action/lang';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AntIcon from 'react-native-vector-icons/AntDesign';


const LanguageSwitcher = (props) => {
    const { t, i18n } = useTranslation();
    const { lang, langList, handleSetLang } = props;

    const current = langList.find(l => l.langType === lang)


    const [visible, setVisible] = useState(false);
    const [currentLang, setCurrentLang] = useState(current?.langTranslate);

    const [searchQuery, setSearchQuery] = useState('');

    const [filteredLanguages, setFilteredLanguages] = useState(langList);

    useEffect(() => {
        const filtered = langList.filter(lang =>
            (lang.langTranslate || lang.langName).toLowerCase().includes(searchQuery.toLowerCase())
        );
        setFilteredLanguages(filtered || []);
    }, [searchQuery]);

    useEffect(() => {
        if (!visible) {
            setSearchQuery('')
        }
    }, [visible]);

    const handleLanguageChange = (lang) => {
        const { langTranslate, langType } = lang
        handleSetLang(langType);
        i18n.changeLanguage(langType);
        setCurrentLang(langTranslate);
    };
    return (
        <View>
            {/* 右上角语言切换按钮 */}
            <View style={styles.triggerWrapper}>
                <TouchableOpacity
                    style={styles.triggerContainer}
                    onPress={() => setVisible(true)}
                >
                    <Image style={styles.langIcon} source={require('@/assets/images/lang.png')} />
                    <Text style={styles.triggerText}>
                        {currentLang}
                    </Text>
                    <AntIcon name="swap" size={16} color="#666" />
                </TouchableOpacity>
            </View>

            {/* 底部语言选择面板 */}
            <Modal
                transparent={true}
                visible={visible}
                animationType="slide"
                onRequestClose={() => setVisible(false)}
            >
                <View style={styles.backdrop}>
                    <TouchableWithoutFeedback onPress={() => setVisible(false)}>
                        <View style={styles.touchableBackdrop} />
                    </TouchableWithoutFeedback>
                </View>


                <View style={styles.panel}>
                    {/* 顶部操作栏 */}
                    <View style={styles.topBar}>
                        <TouchableOpacity
                            style={styles.closeButton}
                            onPress={() => setVisible(false)}
                        >
                            <Icon name="close" size={20} color="#666" />
                        </TouchableOpacity>
                        <Text style={styles.panelTitle}>{t('sys_chooseLang')}</Text>
                        <View style={styles.spacer} />
                    </View>

                    {/* 搜索栏 */}
                    <View style={styles.searchContainer}>
                        <Icon name="search" size={20} color="#999" style={styles.searchIcon} />
                        <TextInput
                            style={styles.searchInput}
                            placeholder={t('sys_select')}
                            placeholderTextColor="#999"
                            value={searchQuery}
                            onChangeText={setSearchQuery}
                            autoFocus={Platform.OS === 'android'}
                        />
                        {searchQuery.length > 0 && (
                            <TouchableOpacity
                                style={styles.clearButton}
                                onPress={() => setSearchQuery('')}
                            >
                                <Icon name="close" size={18} color="#999" />
                            </TouchableOpacity>
                        )}
                    </View>

                    <View style={styles.languageList}>
                        {filteredLanguages.map((language) => (
                            <TouchableOpacity
                                key={language.code}
                                onPress={() => {
                                    handleLanguageChange(language);
                                    setTimeout(() => setVisible(false), 150);
                                }}
                            >

                                <View style={styles.optionContainer}>

                                    <Text style={[
                                        styles.optionText,
                                        currentLang === language.langTranslate && styles.optionTextSelected
                                    ]}>
                                        {language.langTranslate || language.langName}
                                    </Text>
                                    {/* 圆形外框 */}
                                    <View style={[
                                        styles.radioCircle,
                                        currentLang === language.langTranslate && styles.radioCircleSelected
                                    ]}>
                                        {/* 对勾图标 */}
                                        {currentLang === language.langTranslate && (
                                            <Icon
                                                name="check"
                                                size={16}
                                                color="#fff"
                                                style={styles.checkIcon}
                                            />
                                        )}
                                    </View>

                                </View>

                            </TouchableOpacity>
                        ))}
                    </View>
                </View>
            </Modal>
        </View>
    );
};

export default connect(
    state => ({
        lang: state.lang.lang,
        langList: state.lang.langList,
    }),
    dispatch => ({
        handleSetLang: lang => dispatch(handleSetLang(lang)),
    }),
)(LanguageSwitcher);

const styles = StyleSheet.create({
    // 触发按钮样式
    triggerWrapper: {
        position: 'absolute',
        top: 10, // 根据平台调整位置
        right: 0,
        zIndex: 1, // 确保按钮在其他内容上方
    },
    triggerContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 6,
        paddingHorizontal: 6,
        borderRadius: 8,
        backgroundColor: 'rgba(255,255,255,0.9)', // 半透明白色背景
        borderWidth: 1,
        borderColor: '#e8e8e9',
        shadowColor: '#000',
    },
    triggerText: {
        fontSize: 14,
        color: '#000000e6',
        marginHorizontal: 8,
    },

    langIcon: {
        width: 20,
        height: 20,
    },

    // 模态框背景
    backdrop: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.3)',
    },
    touchableBackdrop: {
        flex: 1,
    },


    // 选择面板
    panel: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 12,
        borderTopRightRadius: 12,
        paddingTop: 12,
        paddingBottom: Platform.select({ ios: 24, android: 16 }),
        maxHeight: '80%',
    },

    languageList: {
        marginVertical: 8,
    },

    // 顶部操作栏
    topBar: {
        position: 'relative',
        paddingHorizontal: 8,
        // height: 36,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    closeButton: {
        position: 'absolute',
        padding: 4,
        zIndex: 1,
        top: 5,
        left: 12,
    },
    panelTitle: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333',
        textAlign: 'center',
        lineHeight: 36,
    },
    spacer: {
        width: 24,
    },

    // 搜索栏
    searchContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#f5f5f5',
        borderRadius: 8,
        marginHorizontal: 16,
        marginVertical: 12,
        paddingHorizontal: 12,
        height: 40,
    },
    searchIcon: {
        marginRight: 8,
    },
    searchInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
        paddingVertical: 0,
    },
    clearButton: {
        padding: 4,
        marginLeft: 8,
    },

    // 选项样式
    optionContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 14,
        paddingHorizontal: 8,
    },
    radioCircle: {
        width: 22,
        height: 22,
        borderRadius: 11,
        borderWidth: 1.5,
        borderColor: '#ccc',
        marginRight: 12,
        justifyContent: 'center',
        alignItems: 'center',
    },
    radioCircleSelected: {
        borderColor: '#FE5E08',
        backgroundColor: '#FE5E08'
    },
    checkIcon: {
        marginTop: 1, // 微调对勾位置
    },
    optionText: {
        fontSize: 16,
        color: '#333',
        marginLeft: 12,
    },
    optionTextSelected: {
        // color: '#e6a23c',
    },
});
